class UsersController < ApplicationController

  include CartsHelper

  before_filter :authenticate, :except => [:new, :create]
  before_filter :correct_user, :only => [:show, :edit, :update]
  before_filter :admin_user, :only => [:destroy, :index]

  # GET /users
  # GET /users.json
  def index
    @users = User.paginate(:page => params[:page])

    respond_to do |format|
      format.html # checkout.html.erb
      format.json { render json: @users }
    end
  end

  # GET /users/1
  # GET /users/1.json
  def show
    @user = User.find(params[:id])
    @orders = Cart.order("updated_at DESC").where(:order_placed => true).find_all_by_user_id(@user.id);
  end

  # GET /users/new
  # GET /users/new.json
  def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(params[:user])

    if @user.save
      unless signed_in?
        sign_in @user
      end
      flash[:success] = t "user.account.successfully_created"
      redirect_to @user
    else
      render action: "new"
    end
  end

  def update
    @user = User.find(params[:id])

    if @user.update_attributes(params[:user])
      sign_in(@user)
      flash[:success] = t "user.update.successful"
      redirect_to @user
    else
      flash[:error] = t "user.update.error"
      render action: "edit"
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :ok }
    end
  end

  private

  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user) || current_user.admin?
  end

end
